<?php
Yii::import('application.models.TipoCompra');
Yii::import('application.models.TipoContratacion');
Yii::import('application.vendors.*');
require_once('PHPMailer/class.phpmailer.php');

class AlertasController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','create','update','admin','delete'),
				'users'=>Yii::app()->getModule('user')->getAdmins(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Alertas;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Alertas']))
		{
			$model->attributes=$_POST['Alertas'];
			
			$objetoTipoContratacion = TipoContratacion::model()->findByPk($model->tipo_contratacion);						
			
			if($model->monto <= $objetoTipoContratacion->rango_fin && $model->monto >= $objetoTipoContratacion->rango_inicio && isset($objetoTipoContratacion))
			{
				if($model->fecha_inicio == $model->fecha_fin)
				{	
					//Validacion si las fechas son iguales, se agrega un dia																
					$date = new DateTime($model->fecha_fin);
					$date->add(new DateInterval('P1D'));
					$model->fecha_fin = $date->format('Y-m-d') ;	
				}
				
				$model->fecha_creacion=date('Y-n-j g:i:s');
				$model->fecha_modificacion=date('Y-n-j g:i:s');
				
				
				$model->usuario_creacion = Yii::app()->user->id;
				$model->usuario_modificacion = Yii::app()->user->id;
				
				if($model->save())
				{
					$phpMailer = new PHPMailer();
					$phpMailer->SetFrom("alarmas@manta-online.com","Gestor de Alarmas");
					
					$destinatarios = Notificacion::model()->findAll();				
					foreach ($destinatarios as $destinatario)				
						$phpMailer->AddAddress($destinatario->correo,$destinatario->nombre);
						
					$phpMailer->Subject = 'NUEVA ALERTA CREADA - PROCESO '.$model->codigo_proceso;
					
					$message = strtoupper(Yii::app()->user->name).' HA CREADO UNA NUEVA ALARMA DEL PROCESO '.$model->codigo_proceso."\r\n".
					'El objeto del proceso es '.$model->objeto."\r\n".
					'Fecha de Inicio: '.$model->fecha_inicio."\r\n".
					"Fecha Fin: ".$model->fecha_fin."\r\n".
					'Proveedor: '.$model->proveedor0->razon_social."\r\n".
					"Porcentaje de Alerta %: ".$model->porcentaje;
					
					$phpMailer->Body = $message;
					
					$phpMailer->Send();								
				
					$this->redirect(array('index'));
					
				}
			}
			else
			{
				$model->addError('tipo_contratacion', "Favor de seleccionar el tipo de contratacion y el tipo de compra.");
				$model->addError('monto', 'El monto no se encuentra entre el rango $ '.$objetoTipoContratacion->rango_inicio.' - $ '.$objetoTipoContratacion->rango_fin." perteneciente al tipo de contratación ".$objetoTipoContratacion->nombre);			
			}
			
		}
		
		

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Alertas']))
		{
			$model->attributes=$_POST['Alertas'];
			$model->fecha_modificacion=date('d-m-YYYY');			
			$model->usuario_modificacion = Yii::app()->user->id;
			if($model->save())
				$this->redirect(array('view','id'=>$model->idalertas));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Alertas',
		array('criteria'=>array(
		        'condition'=>'t.on=1',
		        'order'=>'t.fecha_fin ASC,t.codigo_proceso',
//		        'with'=>array('author'),
    			),
    			'pagination'=>array('pageSize'=>20),
    		)
		);						
		
		
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Alertas('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Alertas']))
			$model->attributes=$_GET['Alertas'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Alertas::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='alertas-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
